
/**
 * alarmSynAnalysis
 */

var abnomalVehicle = {
    init : function(){
    	var me = this;
    	me.timeType="day";
    	me.dateTime="";
    	me.queryType="ent";
    	me.queryContent="";
    	me.initweek();
    	me.initEvent();//加载查询菜单
        me.initQueryTime();//初始化查询时间
        me.barChart = this.initBarChart();
        me.loadVehicleList();
        me.loadEnterpriseList();
        //$("#queryBtn").trigger("click");
        me.queryBarChartData();
        me.queryAbnomalVehicleTable();
    },
	initEvent : function(){
		var me = this;
		//业户和车牌号选择按键
		$("#choseSelect").on('change',function(){
			var chose = $("#choseSelect").val();
			if (chose == "vehicle") {
				$("#selectEnterprise").hide();	
				$("#selectVehicle").show();
			}else if (chose == "enterprise") {
				$("#selectVehicle").hide();
				$("#selectEnterprise").show();
			}
		});
		$("#choseSelect").select2();
		//时间天/月选择按键
		$("#timeSelect").on('change',function(){
			var chose = $("#timeSelect").val();
			if (chose == "day") {
				$("#inputDayDate").show();	
				$("#inputMonthDate").hide();
				$("#week").hide();
			}else if (chose == "week") {
				$("#inputDayDate").hide();
				$("#week").show();
				$("#inputMonthDate").hide();
			}else if (chose == "mon"){
				$("#inputDayDate").hide();
				$("#week").hide();
				$("#inputMonthDate").show();
			}
		});
    	$("#queryBtn").on('click',function(){
			if ($("#choseSelect").val() == "vehicle") {
				me.queryType="veh";
				me.queryContent=$.trim($("#selectVehicleSel").val());
			}else if ($("#choseSelect").val() == "enterprise") {
				me.queryType="ent";
				me.queryContent=$.trim($("#selectEnterpriseSel").val());
			}
			var timeType = $("#timeSelect").val();
			me.timeType=timeType;
			if (timeType == "day") {
				me.dateTime=$("#inputDayDate").val();
			}else if (timeType == "week") {
				me.dateTime=$("#week").val();
			}else if (timeType == "mon"){
				me.dateTime=$("#inputMonthDate").val();
			}
			me.queryBarChartData();
			//me.queryAbnomalVehicleTable();
        	$("#resultTable").flexOptions({
	            	url: appCtx + "/report/abnomalVe/getAbnomalVeTable.html?time="+ new Date().getTime(),
	                params: [{
	                	name: 'timeType',
	                    value: me.timeType
	                }, {
	                    name: 'dateTime',
	                    value: me.dateTime
	                }, {
	                	name:"queryType",
	            		value:me.queryType
	                }, {
	                    name: 'queryContent',
	                    value: me.queryContent
	                }],//设置查询参数
	                newp: 1
	            }).flexReload();
    	});
    	$("#exportExcel").on('click',function(){
    		me.exportSimCard();
    	});
        $("#confirmExport").click(function () {
        	me.exportComfirm();
        })
     	$("img[name='trackPlayBtn']").bind('click',function(){});
    },
    //初始化查询时间
    initQueryTime : function(){
    	var me=this;
    	//初始化显示前一天
    	var todayDate = new Date();
    	var date = new Date(todayDate-86400000);
	    var y = date.getFullYear();    
	    var m = date.getMonth() + 1;    
	    m = m < 10 ? ('0' + m) : m;    
	    var d = date.getDate();    
	    d = d < 10 ? ('0' + d) : d; 
    	var day = y+"-"+m+"-"+d;
    	$("#inputDayDate").val(day);
    	me.dateTime=day;
    	var mon = date.getMonth();
    	if (Number(d)>24) {
    		mon = mon + 1;
		}
    	mon = mon < 10 ? ('0' + mon) : mon; 
    	var month = y+"-"+mon;
    	$("#inputMonthDate").val(month);
    },
	//初始化周维度
	initweek : function(){
		$.ajax({
			type : 'post',
			url : appCtx + "base/report/PlatformAnalyzes/queryweek.html",
			cache : false,
			dataType : "JSON",
			success : function(data) {
				if(data!=null&&data!=''){
					$.each(data,function(entryIndex,entry) {
						$("#week").append("<option value='"+entry.value+"'>"+entry.text+"</option>");
					});
				}
			}
		});
	},
    //加载车牌号列表
    loadVehicleList : function(){
    	$("#selectVehicleSel").select2({
	        theme: "default",
	        allowClear: true,
	        placeholder: "全部车辆",
	        ajax:{
	            url:appCtx + "/system/common/selectVehicle.html",
	            dataType:"json",
	            delay:250,
	            data:function(params){
	                return {
	                    name: params.term,
	                    page: params.page || 1
	                };
	            },
	            cache:true,
	            processResults: function (res, params) {
			    	if(res){
			    		var options = [];
			    		var option = {"id":" ", "text":"全部车辆"};
			    		options.push(option);
	    				$.each(res,function(index,obj) {
	    					var option = {"id":obj.id, "text":obj.vehicle_no};
    	                    options.push(option);
	    				});
    	                return {
    	                	results: options,
    	                    pagination: {
    	                        more:false
    	                    }
    	                };
			    	}
	            },
	            escapeMarkup: function (markup) { return markup; },
	            minimumInputLength: 1
	        }
	    });
//        $.ajax({
//            type: 'post',
//            url: appCtx + "/report/alarmSyn/queryVehicleListByRole.html?time="+ new Date().getTime(),
//            cache: true,
//            async : true,
//            dataType: "JSON",
//            success: function (data) {			
//    			if(data){  				
//    				var selectStr="";
//    				selectStr+="<option value=''>全部车辆</option>";
//    				$.each(data,function(entryIndex,entry) {
//    					selectStr+="<option value='"+entry.vehicle_no+"'>"+entry.vehicle_no+"</option>";
//    				});
//    				$('#selectVehicleSel').html(selectStr);
//    				$("#selectVehicleSel").select2();
//    			}
//            }
//        }); 
    },
    //加载业户列表
    loadEnterpriseList:function(){
    	 $('#selectEnterpriseSel').select2({
    		theme: "default",
 	        allowClear: true,
 	        placeholder: "全部业户",
 	        ajax:{
 	            url:appCtx + "/report/alarmSyn/queryEntAndPlatByRole.html?time="+ new Date().getTime(),
 	            dataType:"json",
 	            delay:250,
 	           async : true,
 	            data:function(params){
 	                return {
 	                    name: params.term,
 	                    page: params.page || 1
 	                };
 	            },
 	            cache:true,
 	            processResults: function (res, params) {
 			    	if(res){
 			    		var options = [];
 			    		var option = {"id":" ", "text":"全部业户"};
 			    		options.push(option);
 	    				$.each(res,function(index,obj) {
 	    					var option = {"id":obj.entId, "text":obj.entName};
     	                    options.push(option);
 	    				});
     	                return {
     	                	results: options,
     	                    pagination: {
     	                        more:false
     	                    }
     	                };
 			    	}
 	            },
 	            escapeMarkup: function (markup) { return markup; },
 	            minimumInputLength: 1
 	        }
    	})
	     /*$.ajax({
	         type: 'post',
	         url: appCtx + "/report/alarmSyn/queryEntAndPlatByRole.html?time="+ new Date().getTime(),
	         delay:250,
	         data:function(params){
	                return {
	                    name: params.term,
	                    page: params.page || 1
	                };
	            },
	         cache: true,  
	          processResults: function (res, params) {
			    	if(res){
			    		var options = [];
			    		var option = {"id":" ", "text":"全部业户"};
			    		options.push(option);
	    				$.each(res,function(index,obj) {
	    					var option = {"id":obj.entId, "text":obj.entName};
 	                    options.push(option);
	    				});
 	                return {
 	                	results: options,
 	                    pagination: {
 	                        more:false
 	                    }
 	                };
			    	}
	            },
	            escapeMarkup: function (markup) { return markup; },
	            minimumInputLength: 1*/
	        
	         /*async : true,
	         dataType: "JSON",
	         success: function (data) {			
	 			if(data){  				
	 				var selectStr="";
	 				selectStr+="<option value=''>全部业户</option>";
	 				$.each(data,function(entryIndex,entry) {
	 					selectStr+="<option value='"+entry.entId+"'>"+entry.entName+"</option>";
	 				});
	 				$('#selectEnterpriseSel').html(selectStr);
	 				$("#selectEnterpriseSel").select2();
	 			}
	        	 
	         }
	     });*/
    },
    // 获取查询条件
    getparams: function () {
    	var me = this;
        var params = [{
        	name: 'timeType',
            value: me.timeType
        }, {
            name: 'dateTime',
            value: me.dateTime
        }, {
        	name:"queryType",
    		value:me.queryType
        }, {
            name: 'queryContent',
            value: me.queryContent
        }];
        return params;
    },
	
	/**
	 * 问题车辆柱状图
	 */
    initBarChart : function(){
    	var me = this;
        var option = {
        		/*title:{text:'企业问题车辆统计',x:'center',textStyle:{fontSize:'12px'} },*/
        		color : ['#3398DB'],
        		tooltip : {
	                trigger: 'axis'
	            },
	            legend: {
	                data:['业户名称']
	            },
	            grid: {
			        left: 46,
			        top:'10%',
			        right: 12,
			        containLabel: true
			    },
	            xAxis : [
	                {	
	                	type : 'category',
			            data : []
	                }
	            ],
	            yAxis : [
	                {
	                    type : 'value',
	                    min: 0,
				    	minInterval: 1,
				    	axisLabel: {
		                      formatter: function (value, index) {
		                    	  if (value >= 1 || value == 0) {
		                            	if (value%1 === 0) {
		                            		return value;
		                            	}
		                            }
		                        }
		                 },
	                    name: '车辆数/辆'
	                }
	            ],
	            series : [
	            	{
			            name:'问题车辆数',
			            type:'bar',
			            data:[],
			            barMaxWidth : 100
			            /*markPoint : {
			            data : [
			                    {type : 'max', name: '最大值'},
			                    {type : 'min', name: '最小值'}
			                ]
			            }*/
	            	 }
	            ],
			    dataZoom: [
			    	{
			        start: 0,
			        end: 100,
			        fillerColor:'#A3E1A3',
			        handleColor:'#83A7D1',
			        showDetail:false
			    }]
	        };
        var myChart = echarts.init(document.getElementById('chartAbnomalVe'));
        myChart.setOption(option);
        window.onresize = myChart.resize;
        myChart.on('click', function(param){
         	var enterpriseList = me.enterpriseList;
         	me.queryContent = enterpriseList[param.dataIndex];
        	me.queryType="ent";
        	$("#resultTable").flexOptions({
	            	url: appCtx + "/report/abnomalVe/getAbnomalVeTable.html?time="+ new Date().getTime(),
	                params: [{
	                	name: 'timeType',
	                    value: me.timeType
	                }, {
	                    name: 'dateTime',
	                    value: me.dateTime
	                }, {
	                	name:"queryType",
	            		value:me.queryType
	                }, {
	                    name: 'queryContent',
	                    value: me.queryContent
	                }],//设置查询参数
	                newp: 1
	            }).flexReload();
        });
        return {
         	refash : function(option){
                myChart.setOption(option);
        	},
        	option : option,
        	barChartDom : myChart
        };
    },
	/**
	 * 加载柱状图数据
	 */
	queryBarChartData: function(){
		var me = this;
		$.ajax({
			type : 'post',
			data:abnomalVehicle.getparams(),
			async : true,
			url : appCtx+"/report/abnomalVe/queryAbnomalVeBarChart.html?time="+ new Date().getTime(),
			cache : false,
			dataType : "JSON",
			success : function(data) {
				var option = me.barChart.option;
				option.xAxis[0].data =data.xAxisData; //['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
				option.series[0].data =data.series;// [10, 52, 200, 334, 390, 330, 220];
				me.barChart.refash(option);
				me.enterpriseList = data.entIds;
		
			}
		});
	},   
	/**
     * @Description: 用户单击条形图的某一条,获取条形图的业户ID查询业户异常车辆列表方法
     * @param vehicleId
     * @param plateNumber
     */
	queryAbnomalVehicleTable:function(){
		$("#resultTable").flexigrid({
			url : appCtx + "/report/abnomalVe/getAbnomalVeTable.html?time="+ new Date().getTime(),
			dataType : 'json',
			colModel : abnomalVehicle.getColumn(),
			params: abnomalVehicle.getparams(),
            contentType: "application/json; charset=utf-8",
			resizable : false,
			sortname : "overspeed_order",// 第一次加载数据时排序列
			sortorder : "desc",// 第一次加载数据时排序类型
			usepager : true,// 是否分页，默认为true。
			showToggleBtn : false,
			minheight: 30, //列的最小高度
			nowrap: true, //是否不换行
			showTableToggleBtn : true,// 是否显示收起/打开按钮,默认不显示。
			useRp : true,// 是否可以动态设置每页显示的结果数，默认为false。
			rp : 10,// 每页记录数，默认为10
			rpOptions: [5, 10, 20,50, 100], // 每页结果数
			checkbox : false,// 是否要多选框,默认为false。
			rowId : 'vehicleId',// 多选框绑定行的id,只有checkbox : true时才有效。
			singleSelect : true,
			widthType:"%",
			width : $(".detail-report").width(),
			height : nav.whiceH[1] -205,
            onSuccess: function (data) {
            /*	$("img[name='trackPlayBtn']").on('click',function(){
		     		var vehicleId = $(this).attr('vehicleId');
		     		var playUrl = appCtx + "/gis/playback/trackPlayBack.html?vehicleID="+vehicleId;
		     	 	window.open(playUrl,"_blank"); 
		     	});
            	global.ajaxLoading.close();*/
            },
     	});
    },
    /**
     * 弹出导出选择页
     */
    exportSimCard: function () {
        var options = $("#resultTable").getOptions();
        var total = options.total;
        if (total == 0) {
            global.ajaxLoading.pop("无导出数据", false, 2000);
            return;
        }
        var pages = options.pages;
        //设置默认的开始结束页
        $("#StartPageIndex").val(1);
        $("#EndPageIndex").val(pages);
        //显示导出窗口
        $("#exportModal").modal('show');
    },
    exportComfirm : function(){
    	 var me = this;
	        var options = $("#resultTable").getOptions();
	        //总记录数
	        var total = options.total;
	        //开始页数
	        var StartPage = $("#StartPageIndex").val();
	        //结束页数
	        var EndPage = $("#EndPageIndex").val();
	        var validate = true;
	        var msg = "";
	        if (!StartPage || StartPage == 0) {
	            msg += "【起始页不能为空或者0】";
	            validate = false;
	        }
	        if (!EndPage || EndPage == 0) {
	            msg += "【结束页不能为空或者0】";
	            validate = false;
	        }

	        if (StartPage && EndPage && EndPage < StartPage) {
	            msg += "【结束页要大于起始页】";
	            validate = false;
	        }
	        if (!validate) {
	            global.ajaxLoading.pop(msg, false, 2000);
	            return;
	        }
	        $('#exportModal').modal('hide');
	        global.ajaxLoading.pop("正在导出,请稍后.....", true, 2000);
	        //每页大小
	        var pagesize = options.rp;
	        //获取导出的参数
	        var exportParams = options.exportParams;
	        if ((EndPage - StartPage + 1) * pagesize > 60000 && total > 60000) {
	        	global.ajaxLoading.pop("最多只能导出60000条数据", true, 2000);
	            return
	        }
	        var columns = abnomalVehicle.getExColumn();
	        var header1 = JSON.stringify(columns);
	        var colModelList = new Array();//表头

			 var imageUrl = me.barChart.barChartDom.getDataURL({
					type: 'png',
				    pixelRatio: 1
			}); 
			//图片
			var imgsrcList=new Array();
			imgsrcList.push(imageUrl);
			var imgsrc= $.toJSON(imgsrcList);
				
	        colModelList.push(header1);
	        var colModel = $.toJSON(colModelList);
	        var paramsGrid = {
	           colModel: colModel,
	            title: "问题车辆表",
                timeType:me.timeType,
	            dateTime:me.dateTime,
	            queryType:me.queryType,
	            queryContent:me.queryContent,
	            imgsrc: imgsrc,
	            StartSize: (StartPage-1)*pagesize,
	            PageSize: (EndPage-StartPage+1)*pagesize
	        };
	        post(appCtx + "/report/abnomalVe/exportQueryResult.html", paramsGrid);
	},

    getColumn:function(){
    	return [{
            display : '序号',
            name : 'vehicleId',
            width : 3,
            sortable:false,
            align : 'left',
        },{
            display : '操作',
            name : 'Handler',
            width : 3,
            sortable:false,
            align : 'left',
            paramcolnames:['vehicle_no',"vehicle_color"],
            handlefunction:abnomalVehicle.getPlayBack
        },{
            display : '车牌号',
            name : 'vehicle_no',
            width : 6,
            sortable:false,
            align : 'left',
        },{
            display : '颜色',
            name : 'vehicle_color_name',
            width : 3,
            align : 'left',
            sortable:false,
        },{
            display : '所属业户',
            name : 'enterprise_name',
            width : 18,
            align : 'left',
            sortable:false,
            showTitle:true
        },{
            display : '连续无定位天数>=10(天)',
            name : 'notrack_day_count',
            width : 12,
            align : 'left',
            sortable:false,
            paramcolnames:['notrack_day_count'],
            handlefunction:abnomalVehicle.getNoGpsInfo
        },{
            display : '轨迹完整度<85(%)',
            name : 'track_complete_rate',
            width : 9,
            //className:'cursor',
            align : 'left',
            sortable:false,
            paramcolnames:['track_complete_rate'],
            handlefunction:abnomalVehicle.getTrackComRate
        },{
            display : '轨迹数据合格率<95(%)',
            name : 'data_correct_rate',
            width : 11,
            align : 'left',
            sortable:false,
            showTitleTip: '经度、纬度、速度、海拔、定位时间、方向在5号令要求的范围内就算合格',
            paramcolnames:['track_normal','exception_track_count'],
            handlefunction:abnomalVehicle.getCorrectRate
        },{
            display : '轨迹数据漂移>6(次)',
            name : 'location_exception_count',
            width : 9,
            align : 'left',
            sortable:false,
            showTitleTip: '轨迹数据定位到另外一个错误的位置就算漂移',
            paramcolnames:['location_exception_count'],
            handlefunction:abnomalVehicle.getLoExcetion
        },{
            display : '超速次数(次)',
            name : 'overspeed_100_count',
            width : 8,
            align : 'left',
            sortable:false,
            paramcolnames:['overspeed_100_count'],
            handlefunction:abnomalVehicle.getOverSpeed
        },{
            display : '超速次数排名',
            name : 'overspeed_order',
            width : 7,
            align : 'left',
            sortable:false,
            paramcolnames:['overspeed_order'],
            handlefunction:abnomalVehicle.getOverSpeedOrder
        },{
            display : '累计疲劳驾驶时长(分钟)',
            name : 'tired_duration',
            width : 10,
            align : 'left',
            sortable:false,
            paramcolnames:['tired_duration'],
            handlefunction:abnomalVehicle.getTiredTime
        }]
    },
		//查询列表中的方法
		getNoGpsInfo : function(noGpsInfo){
			var count = parseInt(noGpsInfo);
			var str = "";
			if (count > 10) {
				str = "<span Style='color:red;font-size:12px;'>"+count+"</span>"
			}else{
				str = "<span Style='color:green;font-size:12px;'>"+"-"+"</span>"
			}
			return str;
		}, 
		getTrackComRate : function(num){
			var rate = parseFloat(num);
			var str = (rate).toFixed(2);
			if (rate < 85) {
				str = "<span Style='color:red;font-size:12px;'>"+str+"</span>"
			}else{
				str = "<span Style='color:green;font-size:12px;'>"+"-"+"</span>"
			}
			return str;
		}, 
		getCorrectRate : function(nomal,abnomal){
			var count_n = parseInt(nomal);
			var count_ab = parseInt(abnomal);
			var rate = parseFloat(count_n/(count_n+count_ab));
			var str = (rate*100).toFixed(2);
			if (rate < 0.95) {
				str = "<span Style='color:red;font-size:12px;'>"+str+"</span>"
			}else{
				str = "<span Style='color:green;font-size:12px;'>"+"-"+"</span>"
			}
			return str;
		}, 
		getLoExcetion : function(num){
			var count = parseInt(num);
			var str = "";
			if (count > 6) {
				str = "<span Style='color:red;font-size:12px;'>"+count+"</span>"
			}else{
				str = "<span Style='color:green;font-size:12px;'>"+"-"+"</span>"
			}
			return str;
		}, 
		getOverSpeed : function(num){
			var count = parseInt(num);
			var str = "";
			if (count > 0) {
				str = "<span Style='color:red;font-size:12px;'>"+count+"</span>"
			}else{
				str = "<span Style='color:green;font-size:12px;'>"+"-"+"</span>"
			}
			return str;
		},
		getOverSpeedOrder: function(num){
			var str = "";
			if (num==""|| num == null) {
				str = "<span>"+"-"+"</span>"
			}else{
				var count = parseInt(num);
				if(count <= 0){
					str = "<span>"+"-"+"</span>"
				}else{
					str = "<span Style='font-size:12px;'>"+count+"</span>"
				}
			}
			return str;
		},
		getTiredTime : function(num){
			var count = parseInt(num);
			var str = count.toString() ;
			if (count > 0 ) {
				str = "<span Style='color:red;font-size:12px;'>"+(count/60).toFixed(2)+"</span>"
			}else{
				str = "<span Style='color:green;font-size:12px;'>"+"-"+"</span>"
			}
			return str;
		},
		getPlayBack:function(vehicle_no,vehicle_color){
			var dayTime = $("#inputDayDate").val();
			var start_time = dayTime+" 00:00:00";
			var end_time = dayTime+" 23:59:59";
			var base64 = new Base64();
			var vehicle_no_color = vehicle_no+"_"+vehicle_color;
         	var handleStr = "<a target='_blank' href='"+appCtx + "/gis/playback/trackPlayBack.html?vehicle_no_color="+base64.encode(vehicle_no_color)+
         				"&starttime="+start_time+"&endtime="+end_time+"'>" +
         				"<img name='trackPlayBtn' src='"+global.url.domain+"gps-web/resources/images/track.png' title='轨迹回放'>" +"</a>";		
     		return handleStr;
         },
	    getExColumn:function(){
	    	return [{
	            display : '序号',
	            name : 'vehicleId',
	            width : 80,
	            align : 'left',
	        },{
	            display : '车牌号',
	            name : 'vehicle_no',
	            width : 100,
	            align : 'left',
	        },{
	            display : '颜色',
	            name : 'vehicle_color_name',
	            width : 80,
	            align : 'left',
	        },{
	            display : '所属业户',
	            name : 'enterprise_name',
	            width : 240,
	            align : 'left',
	        },{
	            display : '连续无定位天数>=10(天)',
	            name : 'notrack_day_count',
	            width :180,
	            align : 'left',
	        },{
	            display : '轨迹完整度<85(%)',
	            name : 'track_complete_rate',
	            width : 150,
	            align : 'left',
	        },{
	            display : '动态数据合格率<95(%)',
	            name : 'data_correct_rate',
	            width : 150,
	            align : 'left',
	        },{
	            display : '远距离漂移>6(次)',
	            name : 'location_exception_count',
	            width : 150,
	            align : 'left',
	        },{
	            display : '超速次数(次)',
	            name : 'overspeed_100_count',
	            width : 100,
	            align : 'left',
	        },{
	            display : '超速次数排名',
	            name : 'overspeed_order',
	            width : 120,
	            align : 'left',
	        },{
	            display : '累计疲劳驾驶时长(分钟)',
	            name : 'tired_duration',
	            width : 200,
	            align : 'left',
	        }]
	    },
};
$(function(){
	abnomalVehicle.init();
});

function showAddress(id,start_lon,start_lat){
	var ctrl="#"+id;
	var geocoder = new AMap.Geocoder({
        radius: 1000,
        extensions: "all"
    });        
    geocoder.getAddress(new AMap.LngLat(start_lon,start_lat), function(status, result) {
        if (status === 'complete' && result.info === 'OK') {
        	var address=result.regeocode.formattedAddress;
        	$(ctrl).html(address);
        	$(ctrl).attr("title",address);
        }
    });    
}

